$(function (){
    setInterval(() => {
        countDown('2023-6-23 23:59:59');
    }, 1000);
//处理倒计时功能
    function countDown(time){
        let nowTime = +new Date();
        let inputTime = +new Date(time);
        //秒数
        let times = (inputTime - nowTime)/1000;
        let h = parseInt(times/60/60%24);
        h = h < 10 ? '0'+h : h;
        let m = parseInt(times/60%60);
        m = m < 10 ? '0'+m : m;
        let s = parseInt(times%60);
        s = s < 10 ? '0'+s : s;
        $(".timmer-hour").text(h);
        $(".timmer-minute").text(m);
        $(".timmer-second").text(s);
    }
//完成限时轮播图
    window.addEventListener('load', function () {
        // 获取元素
        var arrow_1 = document.querySelector('.arrow_1');
        var arrow_2 = document.querySelector('.arrow_2');
        var focus = document.querySelector('.seckill-main');
        var focusWidth = focus.offsetWidth;
        // 鼠标经过focus就显示隐藏左右按钮
        focus.addEventListener('mouseenter', function () {
            arrow_1.style.display = 'block';
            arrow_2.style.display = 'block';
            clearInterval(timer);
            timer = null; // 清除定时器变量
        });
        focus.addEventListener('mouseleave', function () {
            arrow_1.style.display = 'none';
            arrow_2.style.display = 'none';
            timer = setInterval(function () {
                arrow_2.click();
            }, 2000);
        });
        var ul = focus.querySelector('ul');
        var ol = focus.querySelector('.circle');

        for (var i = 0; i < ul.children.length; i++) {
            var li = document.createElement('li');
            li.setAttribute('index', i);
            ol.appendChild(li);
            li.addEventListener('click', function () {
                for (var i = 0; i < ol.children.length; i++) {
                    ol.children[i].className = '';
                }
                this.className = 'current';
                var index = this.getAttribute('index');
                animate(ul, -index * focusWidth);
                num = index;
                circle = index;
            })
        }
        olChildren = $(".circle").children()[0];
        olChildren.className = 'current';
        let ulChildren = $("ul").children()[0];
        first = ulChildren.cloneNode(true);
        ul.appendChild(first);
        //点击右侧按钮，图片滚动一张
        var num = 0;
        var circle = 0;
        var flag = true;
        arrow_2.addEventListener('click', function () {
            if (flag) {
                flag = false;
                if (num == ul.children.length - 1) {
                    ul.style.left = 0;
                    num = 0;
                }
                num++;
                animate(ul, -num * 945, function () {
                    flag = true;//打开节流阀
                });
                circle++;
                if (circle == 3) {
                    circle = 0;
                }
                circleChange();
            }
        });
        //左侧按钮
        arrow_1.addEventListener('click', function () {
            if (flag) {
                flag = false;
                if (num == 0) {
                    num = ul.children.length - 1;
                    ul.style.left = -num * focusWidth + 'px';
                }
                num--;
                animate(ul, -num * focusWidth, function () {
                    flag = true;
                });
                circle--;
                circle = circle < 0 ? ol.children.length - 1 : circle;
                circleChange();
            }
        });
        function circleChange() {
            for (let i = 0; i < ol.children.length; i++) {
                ol.children[i].className = '';
            }
            ol.children[circle].className = 'current';
        }
        var timer = setInterval(function () {
            arrow_2.click();
        }, 2000);
    })
    function animate(obj, target, callback) {
        clearInterval(obj.timer);
        obj.timer = setInterval(function () {
            // 步长值写到定时器里面
            var step = (target - obj.offsetLeft) / 10;
            step = step > 0 ? Math.ceil(step) : Math.floor(step);
            if (obj.offsetLeft == target) {
                // 停止动画
                clearInterval(obj.timer);
                callback && callback();
            }
            // 步长公式：（目标值-现在的位置）/10
            obj.style.left = obj.offsetLeft + step + 'px';
        }, 15);
    }
//完成固定右侧导航栏颜色字体变化功能
    $(".toolbar-item").on("mouseenter mouseleave",function(){
        $(this).toggleClass("toolbar-active");
        $(this).find("span").toggleClass("toolbar-active");
    })
//完成返回顶部功能
    let sliderbar = document.querySelector(".toolbar-wrap");
    let mainBox = document.querySelector(".banner-wrap");
    let mainTop = mainBox.offsetTop;
    let toolbar = document.querySelector(".toolbar");

    document.addEventListener("scroll",function(){
        if(window.pageYOffset > 500){
            sliderbar.style.position = 'fixed';
            sliderbar.style.top =250+ 'px';
        }else{
            sliderbar.style.position = 'absolute';
            sliderbar.style.top = '750px';
        }
        if(window.pageYOffset >= mainTop){
            toolbar.style.display = 'block';
        }else{
            toolbar.style.display = 'none';
        }
    })
//完成返回页面顶部功能
    let topBtn = document.querySelector('.return-top');
    topBtn.addEventListener('click', function () {
        returntop(window, 0);
    });
    function returntop(obj, target, callback) {
        clearInterval(obj.timer);
        obj.timer = setInterval(function () {
            var step = (target - window.pageYOffset) / 10;
            step = step > 0 ? Math.ceil(step) : Math.floor(step);
            if (window.pageYOffset == target) {
                clearInterval(obj.timer);
                callback && callback();
            }
            window.scroll(0, window.pageYOffset + step);
        }, 15);
    }



    //发送异步请求加载数据
    fetch("load.index").then(response=>response.json()).then(data=>{
        console.log(data);
        if(data.flag) {
            //获得主横幅数据
            let mainBanner = data.data.mainBanner;
            //获得限时秒杀横幅数据
            let killingBanner = data.data.killingBanner;
            //获得捕头严选数据
            let selected = data.data.selected;
            //获得优选爆款数据
            let recommend=data.data.recommend;
            //进行渲染
            //加载横幅
            loadMainBanners(mainBanner);
            loadKillingBanners(killingBanner);
            //加载捕头严选
            loadSelected(selected);
            //加载优选爆款
            loadRecommend(recommend);
        }else{
            //异常处理
            alert(data.message);
        }
    });

    let mainContainer=document.querySelector("#mainContainer");
    let loadMainBanners=(banners)=>{
        let bannerItems="";
        banners.forEach((b,index)=>{
            bannerItems+=`<div class="carousel-item ${b.order==1?'active':''}">
                            <div class="d-block w-100" style="background-color: ${b.backgroundColor};">
                                <a href="#" class="d-flex justify-content-center">
                                    <!--图片大小为800*450-->
                                    <img src="${b.pic}" alt="" class="img-fluid"></a>
                            </div>
                        </div>`
        })
        console.log(bannerItems);
        mainContainer.innerHTML=bannerItems;
    }

    let killingContainer=document.querySelector("#killingContainer");
    let loadKillingBanners=(banners)=> {
        let bannerItems = "";
        let items = "";
        for (let i = 0; i < banners.length; i++) {
            if ((i + 1) % 3 == 0) {
                bannerItems += `<li style="display: flex;">` + items +
                    `<a href="product.html?pid=${banners[i].pid}" class="seckill-items col-4 px-0">
                                <img src="${banners[i].pic}" alt="">
                                <p class="seckill-tit">${banners[i].name}</p>
                                <p class="seckill-tit-sml">限时最低价：<span class="text-danger">￥${banners[i].price}元</span></p>
                            </a>` +
                    `</li>`;
                items = "";
            } else {
                items += `<a href="product.html?pid=${banners[i].pid}" class="seckill-items col-4 px-0">
                                <img src="${banners[i].pic}" alt="">
                                <p class="seckill-tit">${banners[i].name}</p>
                                <p class="seckill-tit-sml">限时最低价：<span class="text-danger">￥${banners[i].price}元</span></p>
                            </a>`;
            }
        }
        console.log(bannerItems);
        killingContainer.innerHTML = bannerItems;
    }
    let selectedContainer = document.querySelector("#selectedContainer");
    let loadSelected=(selected)=>{
        let selectedItems='';
        selected.forEach((r,index)=>{
            selectedItems+=`<div class="ml-0 col-xl-3 col-lg-4 col-md-6 col-sm-6 px-0 mb-4">
                <div class="card h-100">
                    <div class="card-img">
                        <a href="product.html?pid=${r.pid}">
                            <img src="${r.pimage}" class="card-img-top selected-img" alt="...">
                        </a>
                    </div>
                    <div class="card-body">
                    <a href="product.html?pid=${r.pid}">
                        <h1 class="card-title">${r.name}</h1>
                    </a>
                    <a href="product.html?pid=${r.pid}">
                        <h2 class="card-title text-danger">￥${r.price}</h2>
                    </a>
                    <a href="product.html?pid=${r.pid}">
                        <p class="card-text">${r.desc}</p>
                    </div>
                    </a>
                </div>
            </div>`;
        });
        selectedContainer.innerHTML=selectedItems;
    }


    let recommendContainer=document.querySelector("#recommendContainer");
    let loadRecommend=(recommend)=>{
        let recommendItems='';
        recommend.forEach((r,index)=>{
            recommendItems+=`<div class="ml-0 col-xl-3 col-lg-4 col-md-6 col-sm-6 px-0 mb-4">
                <div class="card h-100">
                    <div class="card-img">
                        <a href="product.html?pid=${r.pid}">
                            <img src="${r.pimage}" class="card-img-top selected-img" alt="...">
                        </a>
                    </div>
                    <div class="card-body">
                        <a href="product.html?pid=${r.pid}">
                        <h1 class="card-title">${r.name}</h1>
                    </a>
                    <a href="product.html?pid=${r.pid}">
                        <h2 class="card-title text-danger">￥${r.price}</h2>
                    </a>
                    <a href="product.html?pid=${r.pid}">
                        <p class="card-text">${r.desc}</p>
                    </div>
                    </a>
                    </div>
                </div>
            </div>`;
        });
        recommendContainer.innerHTML=recommendItems;
    }


    let addCar=pid=>{
        //发送请求
        fetch(`add.car?pid=${pid}&qty=1`).then(response=>response.json()).then(data=>{
            if(data.flag){
                alert(data.message);
            }
        })
    }


    $(".search button").on("click",function (){
        jumpToSearch()
    })
    // search函数
    function jumpToSearch(){
        let SearchInput = document.querySelector("#SearchInput");
        let keyWord = SearchInput.value;
        //对keyWord进行格式校验
        if(keyWord.trim().length == 0){
            //keyWord为空 给出友好提示
            return "空空如也";
        }else {
            location.href="searchProducts.html?keyWord="+keyWord.trim();
        }

    }

    stateManagement();
    function stateManagement(){
        //状态管理
        //判断用户是否登录
        let userInfo = sessionStorage.getItem("shopping.userInfo");
        let User = ``;
        let Car = ``;
        let Img = ``;
        if(userInfo){
            let user = JSON.parse(userInfo);
            let userId = user.id;
            fetch(`loadOrderNum.index?uid=${userId}`).then(response=>response.json()).then(data=>{
                console.log(data);
                $("#notPayment").text(data.data[0]);
                $("#notDeliver").text(data.data[1]);
                $("#notReceiptt").text(data.data[2]);
                $("#finished").text(data.data[3]);
            })
            User=`
        <div id="userWelcome">Hi,欢迎来到环球鞋网
                                <div class="userWelcome-text">
                                    <span id="userUsername">${user.username}</span>
                                    <span id="userQuit">
                                        <a href="javascript:;" id="quit">
                                            退出登录
                                        </a>
                                    </span>
                                </div>
                            </div>
        `;
            Car = `
            <a href="car.html">
                        <span class="iconfont icon-gouwuchekong"></span>
                        <span class="tool-text">购物车</span>
                    </a>`;
            Img=`
            <a href="information.html"><img id="userImage" src="images/用户照片.png"></a>
            `;
        }else{
            User = `
    <div id="defaultWelcome">Hi,欢迎来到环球鞋网
                                <div class="defaultWelcome-text">
                                    <span>你好，请先</span>
                                    <a href="login.html">登录</a>
                                    <a href="regist.html">我要注册</a>
                                </div>
                            </div>`;
            Car = `
            <a href="login.html">
                        <span class="iconfont icon-gouwuchekong"></span>
                        <span class="tool-text">购物车</span>
                    </a>`;
            Img=`
            <a href="login.html"><img id="userImage" src="images/用户照片.png"></a>
            `;
        }
        $("#sessionChange").html(`${User}`);
        $(".m-cart").html(`${Car}`);
        $("#userImg").html(`${Img}`);
        $("#quit").on("click",function(){
            sessionStorage.removeItem('shopping.userInfo');
            stateManagement();
            location.reload();
        })
    }
})